# Maintainer: Nazar Mishturak <nazar m x at gmail dot com>

_realname=mbedtls
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.4.1
pkgrel=1
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url='https://tls.mbed.org/'
pkgdesc="Portable cryptographic and SSL/TLS library, aka polarssl (mingw-w64)"
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("${_realname}-${pkgver}.tar.gz"::"https://github.com/ARMmbed/mbedtls/archive/v${pkgver}.tar.gz"
        'enable-features.patch')
sha256sums=('a420fcf7103e54e775c383e3751729b8fb2dcd087f6165befd13f28315f754f5'
            'e8ccbbdb60323ebb9f25aa54b1e7b60b5d2f17d30d27dd20c349951fe55dd620')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  apply_patch_with_msg \
    enable-features.patch
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  CXXFLAGS+=" -Wno-documentation" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    "${_extra_config[@]}" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DENABLE_PROGRAMS=ON \
    -DENABLE_TESTING=OFF \
    -DMBEDTLS_FATAL_WARNINGS=OFF \
    -DUSE_SHARED_MBEDTLS_LIBRARY=ON \
    -DUSE_STATIC_MBEDTLS_LIBRARY=ON \
    -DLINK_WITH_PTHREAD=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake.exe \
    -DENABLE_TESTING=ON \
    ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake.exe --build .
  # Tests are dynamically linked
  PATH=$PWD/library:$PATH ${MINGW_PREFIX}/bin/ctest || true
}

package () {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR=${pkgdir} ${MINGW_PREFIX}/bin/cmake.exe --install .

  # rename generic utils
  local _prog _baseprog
  for _prog in "$pkgdir${MINGW_PREFIX}"/bin/*.exe; do
    _baseprog=$(basename "$_prog")
    mv "$_prog" "${_prog//$_baseprog/mbedtls_$_baseprog}"
  done

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
